<script setup lang='ts'>
import { ref, onMounted, watch} from 'vue'
import { getCategoryListAPI, getFinishListAPI } from '../../apis/novel';
import { RouterLink, useRoute } from 'vue-router'

const route = useRoute()
const list = ref([])
const page = ref(1)

const load = async () => {
  // watch切换到首页时会在请求一次, 这里直接返回
  if (!route.params.type) {
    return
  }
  // 设置标题
  document.title = '笔趣阁_小说分类_' + route.params.type
  // 切换了分类 将list清空
  if(page.value == 1) list.value = []
  const type = route.params.type
  if (type === '完本') {
    const res = await getFinishListAPI(page.value)
    list.value = list.value.concat(res.data)
  } else {
    const res = await getCategoryListAPI(type, page.value)
    list.value = list.value.concat(res.data)
  }
  // 本分类下的下拉刷新
  page.value++
}

// watchEffect 会自动跟踪数据的变化, 以后用来替换onUndated 
// 还是使用watch吧, 指定监听的资源
watch(route, () => {
  // 切换分类时重置页码
  page.value = 1
  load()
})

onMounted(() => {
  load()
})

</script>

<template>
  <div class="min-h-screen text-sm">
    <div class="flex w-full mt-3">
      <div class="flex flex-col w-full min-h-full bg-orange-50">
        <div class="border-2">
          <div
            v-infinite-scroll="load"
            class="grid w-full grid-cols-3 gap-1 px-3 py-1 min-h-20"
          >
            <div
              class="flex rounded-md bg-orange-50 box"
              v-for="item in list"
              :key="item.id"
            >
              <div class="flex items-center pt-2">
                <div class="flex items-center border-2 border-gray-300 lg:inline-block sm:hidden min-w-max">
                  <RouterLink :to="{ path: '/book/' + item.id }">
                    <img
                      src="../../assets/img/null.jpg"
                      :alt="item.name"
                      class="h-auto w-28 min-w-28"
                    >
                  </RouterLink>
                </div>
                <dl class="flex flex-col px-3 max-h-fit">
                  <dt class="flex items-center justify-between border-b border-gray-200 opacity-70">
                    <RouterLink
                      class="w-32 font-bold text-blue-900 nowrap "
                      :to="{ path: '/book/' + item.id }"
                    >
                      {{ item.name }}
                    </RouterLink>
                    <span class="text-sm text-right text-gray-400 w-14 nowrap">{{ item.author }}</span>
                  </dt>
                  <dd class="w-48 h-32 pt-3 text-sm text-gray-400">{{ item.simple }}</dd>
                </dl>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>

<style scoped lang='scss'>
.nowrap {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>